<template>
  <div>
    <div class="mb-3">
      <el-button
        type="primary"
        v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        @click="edit()"
      >
        新增用户名
      </el-button>
      <el-button type="primary" @click="dialogImportVisible = true">
        <i class="fa fa-fw fa-upload"></i>
        导入银行流水
      </el-button>
    </div>

    <loading-wrap>
      <table
        v-for="(p, index) of tableData"
        class="table table-bordered bg-white"
        style="text-align: center"
        :key="index"
      >
        <colgroup>
          <col width="25%" />
          <col width="25%" />
          <col width="20%" />
          <col width="20%" />
          <col width="10%" />
        </colgroup>
        <tr>
          <td>用户名：</td>
          <td>{{ p.bank_account || '-' }}</td>
          <td>类型：</td>
          <td>{{ enumFinanceType[p.finance_bank_type] || '-' }}</td>
          <td v-if="customerData.project_status === '0' || customerData.project_status === '2'">
            操作
          </td>
        </tr>
        <tr>
          <td>银行名称：</td>
          <td>{{ p.bank_name || '-' }}</td>
          <td>银行账号：</td>
          <td>{{ p.bank_no || '-' }}</td>
          <td
            style="vertical-align: middle"
            v-if="customerData.project_status === '0' || customerData.project_status === '2'"
          >
            <el-button type="text" class="py-0 px-2" @click="edit(p)">
              <i class="fa fa-edit"></i>
            </el-button>
          </td>
        </tr>
        <tr>
          <td>日期</td>
          <td>收入</td>
          <td>支出</td>
          <td>备注</td>
          <td v-if="customerData.project_status === '0' || customerData.project_status === '2'">
            <el-button type="text" class="py-0 px-2" @click="p.showAdd = !p.showAdd">
              <i class="fa fa-plus-square" v-show="!p.showAdd"></i>
              <i class="fa fa-minus-square" v-show="p.showAdd"></i>
            </el-button>
          </td>
        </tr>
        <tr v-show="p.showAdd">
          <td>
            <el-date-picker
              v-model="p.date"
              placeholder="选择日期"
              style="width: 100%"
              type="month"
              value-format="yyyy-MM"
              :clearable="true"
            ></el-date-picker>
          </td>
          <td>
            <el-input-number
              v-model="p.flowincome"
              style="width: 100%"
              :controls="false"
            ></el-input-number>
          </td>
          <td>
            <el-input-number
              v-model="p.flowpaid"
              style="width: 100%"
              :controls="false"
            ></el-input-number>
          </td>
          <td>
            <el-input v-model="p.flowremark"></el-input>
          </td>
          <td v-if="customerData.project_status === '0' || customerData.project_status === '2'">
            <el-button
              type="primary"
              @click="postData(p, p.datum_customer_finance_bank_account_id, index)"
              :loading="saveLoading"
            >
              添加
            </el-button>
          </td>
        </tr>
        <tr v-if="!p.data || p.data.length < 1">
          <td colspan="5"><span style="color: gray">暂无数据</span></td>
        </tr>
        <tr v-for="(p, flowindex) of p.data" :key="flowindex">
          <td>{{ p.year || '-' }}</td>
          <td>{{ p.income || '-' }}</td>
          <td>{{ p.paid || '-' }}</td>
          <td>{{ p.remark || '-' }}</td>
          <td v-if="customerData.project_status === '0' || customerData.project_status === '2'">
            <el-button type="text" class="py-0 px-2" @click="editflow(p)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteFlow(p, index)">
              <i class="fa fa-trash"></i>
            </el-button>
          </td>
        </tr>
        <tr v-if="p.sumCol" class="font-weight-bold">
          <td>合计</td>
          <td>{{ p.sumCol.income }}</td>
          <td>{{ p.sumCol.paid }}</td>
          <td colspan="2"></td>
        </tr>
      </table>
    </loading-wrap>
    <form-component
      ref="flow"
      table-name="datum_customer_finance_bank"
      :id-append="false"
      title="修改银行流水"
      :auto-init="false"
      :form-append="{}"
      :form-data="flowPost"
      :table-data="flowEdit"
      @success="getData"
      :table-id="flowId"
      :visible.sync="flowVisible"
    ></form-component>
    <form-component
      ref="fc"
      title="编辑银行用户"
      :auto-init="false"
      :form-append="{ customer_id: 'customer_id' }"
      :form-data="formData"
      :table-data="editData"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editVisible"
      @success="getData"
    >
      <el-button
        v-show="deleteButton"
        class="btn-long"
        slot="button"
        type="primary"
        @click="deleteData(editData)"
      >
        删除
      </el-button>
    </form-component>
    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入银行流水"
      :post-api="postUrl"
      excel-template="/static/files/银行流水导入模板.xlsx"
      @success="handleImportSucess"
    ></import-excel>
  </div>
</template>
<script>
import FormComponent from '@/components/FormComponent'
import { DatePicker } from 'element-ui'
import { enumFinanceType } from '@/credit/plugins/enum'
import ImportExcel from '@/components/ImportExcel'
export default {
  components: {
    FormComponent,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      postUrl: '',
      dialogImportVisible: false,
      enumFinanceType,
      tableData: [],
      saveLoading: false,
      editVisible: false,
      deleteButton: false,
      tableName: 'datum_customer_finance_bank_account',
      tableId: '',
      editData: {},
      formData: {
        bank_account: { type: 'text', label: '用户名', value: '', required: true },
        finance_bank_type: {
          type: 'radio',
          label: '类型',
          value: '1',
          enumType: enumFinanceType,
          inline: true,
        },
        bank_name: { type: 'text', label: '银行名称', value: '' },
        bank_no: { type: 'text', label: '银行账号', value: '' },
      },
      flowPost: {},
      flowId: '',
      flowData: [],
      flowEdit: {},
      flowVisible: false,
    }
  },
  computed: {},
  watch: {},
  created() {
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.postUrl =
      '/api/credit/import/?importKey=datum_customer_finance_bank_template&where=' +
      encodeURIComponent(
        '"datum_customer_finance_bank.service_id".eq(' + this.$store.getters.org.clientId + ')'
      ) +
      encodeURIComponent('&"datum_customer_finance_bank.customer_related_id".eq(' + this.id + ')')

    this.getData()
  },
  mounted() {},
  methods: {
    editflow(p) {
      this.flowId = p ? p.id : ''
      this.flowPost = {
        date: {
          type: 'component',
          label: '日期',
          value: '',
          required: true,
          component: DatePicker,
          redun: true,
          attrs: {
            style: 'width: 360px',
            type: 'month',
            valueFormat: 'yyyy-MM',
          },
          on: {
            input: a => {
              const ref = this.$refs.flow
              ref.setKey('year', 'value', a.replace(/-.*/g, ''))
              ref.setKey('month', 'value', a.replace(/.*-/g, ''))
              ref.setKey('datum_customer_finance_bank_account_id', 'value', this.tableId)
            },
          },
        },
        datum_customer_finance_bank_account_id: {
          type: 'text',
          label: 'id',
          value: '',
          hide: true,
        },
        year: { type: 'number', label: '年', value: '', hide: true },
        month: { type: 'number', label: '月', value: '', hide: true },
        income: { type: 'number', label: '收入', value: '', unit: '元' },
        paid: { type: 'number', label: '支出', value: '', unit: '元' },
        remark: { type: 'text', label: '备注', value: '' },
      }
      if (p) {
        p.date = p.year + '-' + p.month
      }
      this.flowEdit = p
      this.flowVisible = true
    },
    // 导入
    handleImportSucess() {
      this.getData()
      this.dialogImportVisible = false
    },
    getData() {
      this.tableData = []
      this.$api
        .getData('credit', this.tableName, {
          'customer_related_id.eq': this.id,
        })
        .then(res => {
          this.tableData = (res && res.data) || []
          for (let p of this.tableData) {
            this.$set(p, 'showAdd', false)
            this.$api
              .getData(
                'credit',
                'datum_customer_finance_bank',
                {
                  'datum_customer_finance_bank_account_id.eq':
                    p.datum_customer_finance_bank_account_id,
                },
                { N1year: 'asc', N2month: 'asc' }
              )
              .then(res => {
                const data = (res && res.data) || []
                if (data.length) {
                  let income = 0
                  let paid = 0
                  for (let d of data) {
                    income += Number.parseFloat(d.income) || 0
                    paid += Number.parseFloat(d.paid) || 0
                  }
                  this.$set(p, 'sumCol', {
                    income: income.toFixed(2),
                    paid: paid.toFixed(2),
                  })
                } else {
                  this.$set(p, 'sumCol', null)
                }
                this.$set(p, 'data', data)
              })
          }
        })
    },

    getflowData(id, index) {
      this.$api
        .getData(
          'credit',
          'datum_customer_finance_bank',
          {
            'datum_customer_finance_bank_account_id.eq': id,
          },
          { N1year: 'asc', N2month: 'asc' }
        )
        .then(res => {
          const data = (res && res.data) || []
          if (data.length) {
            let income = 0
            let paid = 0
            for (let d of data) {
              income += Number.parseFloat(d.income) || 0
              paid += Number.parseFloat(d.paid) || 0
            }
            this.$set(this.tableData[index], 'sumCol', {
              income: income.toFixed(2),
              paid: paid.toFixed(2),
            })
          } else {
            this.$set(this.tableData[index], 'sumCol', null)
          }
          this.$set(this.tableData[index], 'data', data)
        })
    },

    async postData(data, id, index) {
      let post = {}
      if (!data.date) {
        return this.$message.warning('请选择日期！')
      }
      post.year = data.date
      post.income = data.flowincome
      post.remark = data.flowremark
      post.paid = data.flowpaid
      post.month = data.date.replace(/.*-/, '')
      post.datum_customer_finance_bank_account_id = id
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addData('credit', 'datum_customer_finance_bank', post)
      )
      this.saveLoading = false
      if (res) {
        data.date = ''
        data.flowincome = ''
        data.flowremark = ''
        data.flowpaid = ''
        this.$message.success('添加成功！')
        this.getflowData(id, index)
      } else {
        this.$message.error(`添加失败，请重试！（${err.status}）`)
      }
    },
    edit(p) {
      this.editVisible = true
      this.tableId = p ? p.datum_customer_finance_bank_account_id : ''
      this.deleteButton = !!p
      this.editData = p
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除该用户包括银行流水？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            let data = {
              isRetainMasterInfo: '0',
              masterTableInfo: JSON.stringify({
                datum_customer_finance_bank_account_id: item.datum_customer_finance_bank_account_id,
              }),
              masterTableName: 'datum_customer_finance_bank_account',
              slaveTableName: 'datum_customer_finance_bank',
            }
            const [res] = await this.$utils.promise(this.$api.relatedDelete('credit', data))
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.editVisible = false
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      })
    },
    deleteFlow(item, index) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除该条银行流水？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', 'datum_customer_finance_bank', item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getflowData(item.datum_customer_finance_bank_account_id, index)
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      })
    },
  },
}
</script>
<style scoped></style>
